package com.lkd.handler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lkd.business.MsgHandler;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.service.ChannelService;
import com.lkd.service.VendingMachineService;
import com.lkd.utils.JsonUtil;
import entity.ChannelEntity;
import entity.VendingMachineEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Component
@Topic(TopicConfig.VMS_SUPPLY_TOPIC)
public class TaskReplenishmentMsgHandler implements MsgHandler {

    @Autowired
    private VendingMachineService vendingMachineService;

    @Autowired
    private ChannelService channelService;

    @Override
    @Transactional
    public void process(String jsonMsg) throws IOException {
        SupplyContract contract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
        LambdaQueryWrapper<VendingMachineEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VendingMachineEntity::getInnerCode, contract.getInnerCode());
        VendingMachineEntity entity = vendingMachineService.getOne(wrapper);
        // 设置最后补货时间
        entity.setLastSupplyTime(LocalDateTime.now());
        vendingMachineService.updateById(entity);

        List<ChannelEntity> list = channelService.getChannelesByInnerCode(contract.getInnerCode());
        List<SupplyChannel> supplyData = contract.getSupplyData();
        supplyData.forEach(supplyChannel -> {
            Optional<ChannelEntity> optional = list.stream().filter(channelEntity ->
                    channelEntity.getChannelCode().equals(supplyChannel.getChannelId())
            ).findFirst();
            if (optional.isPresent()) {
                ChannelEntity channelEntity = optional.get();
                // 更新货道库存
                channelEntity.setCurrentCapacity(channelEntity.getCurrentCapacity() + supplyChannel.getCapacity());
                // 更新货道最后补货时间
                channelEntity.setLastSupplyTime(LocalDateTime.now());
                channelService.updateById(channelEntity);
            }
        });
    }
}
